<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/idea.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/edit/closebrackets'
// 折叠代码
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/brace-fold.js'
import 'codemirror/addon/fold/comment-fold.js'
// JSON错误检查
// 引入jsonlint
require('script-loader!jsonlint')
import 'codemirror/addon/lint/lint.css'
import 'codemirror/addon/lint/lint.js'
import 'codemirror/addon/lint/json-lint'
// 及时自动更新，配置里面也需要设置autoRefresh为true
import 'codemirror/addon/display/autorefresh'

export default {
  name: 'JsonEditor',
  props: {
    value: [String, Number, Object, Array],
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value(newVal) {
      if (newVal == null) {
        this.jsonEditor.setValue('')
      }
      const editorValue = this.jsonEditor.getValue()
      if (newVal !== editorValue && newVal != null) {
        this.jsonEditor.setValue(JSON.stringify(JSON.parse(newVal), null, 2))
      }
      // this.jsonEditor.refresh()
    }
  },
  mounted() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      theme: 'idea',
      mode: 'application/json',
      lineNumbers: true,
      indentUnit: 2,
      tabSize: 2,
      smartIndent: true,
      matchBrackets: true, // 括号匹配显示
      autoCloseBrackets: true,
      gutters: ['CodeMirror-lint-markers', 'CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
      lint: true,
      foldGutter: true,
      autoRefresh: true,
      readOnly: this.readOnly
    })

    this.jsonEditor.on('change', (instance) => {
      this.$emit('input', instance.getValue())
    })
    if (this.value != null) {
      this.jsonEditor.setValue(JSON.stringify(JSON.parse(this.value), null, 2))
    }
  },
  methods: {
    getValue() {
      return this.jsonEditor.getValue()
    },
    refresh() {
      this.jsonEditor.refresh()
    }
  }
}
</script>

<style scoped>
.json-editor {
  height: 100%;
  position: relative;
  line-height: 1.5;
  border: 1px solid #d9d9d9;
  border-top-width: 1.02px;
  border-radius: 4px;
}
.json-editor >>> .CodeMirror {
  height: auto;
  min-height: 200px;
}
.json-editor >>> .CodeMirror-scroll {
  min-height: 200px;
}
</style>

<style>
/* 解决 tooltip 被遮挡问题 */
.CodeMirror-lint-tooltip {
  z-index: 3000 !important;
}
</style>
